﻿using System.Security.Cryptography;
using System.Text;
using CoHubServerCore.Algorithm;

namespace CoHubServerCore.Security;

public class Aes
{
    public string Key
    {
        get => Encoding.UTF8.GetString(_aes.Key);
        set
        {
            if (!_aes.ValidKeySize(value.Length * 8))
                throw new ArgumentException();
            _aes.Key = Encoding.UTF8.GetBytes(value);
        }
    }

    private readonly System.Security.Cryptography.Aes _aes = System.Security.Cryptography.Aes.Create();

    private static PaddingMode PaddingMode => PaddingMode.PKCS7;

    public Aes() : this(16)
    {
    }

    public Aes(int length) : this(RandomGenerator.Text(length))
    {
    }

    public Aes(string key)
    {
        Key = key;
    }

    public string Encrypt(string plain)
    {
        return Convert.ToBase64String(_aes.EncryptEcb(Encoding.UTF8.GetBytes(plain), PaddingMode));
    }

    public string? Decrypt(string secret)
    {
        try
        {
            return Encoding.UTF8.GetString(_aes.DecryptEcb(Convert.FromBase64String(secret), PaddingMode));
        }
        catch (CryptographicException)
        {
            return null;
        }
    }
}